package com.ewm.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Hashtable;
@RestController
public class ewmDome {
    @RequestMapping("/test")
    public void test(HttpServletResponse response){
        int BLACK = 0xFF000000;
        int WHITE = 0xFFFFFFFF;
        String text = "https://www.hao123.com/"; //这里是URL ，扫描之后就跳转到这个界面
        int width = 450;
        int height = 450;
        // 二维码图片格式
        String format = "png";
        // 设置编码，防止中文乱码
        Hashtable<EncodeHintType, Object> ht = new Hashtable<>();
        ht.put (EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置二维码参数(编码内容，编码类型，图片宽度，图片高度,格式)
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode (text, BarcodeFormat.QR_CODE, width, height, ht);
            // 生成二维码(定义二维码输出服务器路径)
            int b_width = bitMatrix.getWidth ();
            int b_height = bitMatrix.getHeight ();
            // 建立图像缓冲器
            BufferedImage image = new BufferedImage (b_width, b_height, BufferedImage.TYPE_3BYTE_BGR);
            for ( int x = 0; x < b_width; x++ )
            {
                for ( int y = 0; y < b_height; y++ )
                {
                    image.setRGB (x, y, bitMatrix.get (x, y) ? BLACK : WHITE);
                }
            }
            ImageIO.write(image,format,response.getOutputStream());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
